package com.user.service.impl;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.user.controller.UserController;
import com.user.domain.User;
import com.user.repository.UserRepository;
import com.user.service.UserCacheService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import static org.slf4j.LoggerFactory.getLogger;

@Service
public class UserCacheServiceImpl implements UserCacheService {

    private static final Logger LOGGER = getLogger(UserCacheServiceImpl.class);
    //过期失效时间
    private static final Long EXPIRE_TIME = 30L;

    //保留在缓存中的client尺寸大小。
    private static final Long CACHE_SIZE = 10L;

    private UserRepository userRepository;

    @Autowired
    public UserCacheServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    /**
     * 创建/加载缓存数据
     */
    private final LoadingCache<String,User> cacheUser=CacheBuilder.newBuilder()
            .expireAfterAccess(EXPIRE_TIME,TimeUnit.MINUTES) //未读写
            .expireAfterWrite(EXPIRE_TIME,TimeUnit.MINUTES) //未写
            .maximumSize(CACHE_SIZE)//最大存储量
            .build(new CacheLoader<String, User>() {
                @Override
                public User load(String userName) throws Exception{

                    return userRepository.findUserByUserName(userName);

                }
            });

    @Override
    public User getCacheUser(String userName) {
        try {
            return cacheUser.get(userName);
        } catch (ExecutionException e) {
            LOGGER.error(e.getMessage());
            return null;
        }catch (CacheLoader.InvalidCacheLoadException e2){
            LOGGER.error(e2.getMessage());
            return null;
        }
    }
}
